<template>
    <view class="shopitem item" v-if="objInfo && objInfo.id" @click="linkTo('detail')">
        <view class="store flexb" @click.stop="linkTo('store')" v-if="objInfo.store">
            <view class="store_name flexb">
                <image class="icon" :src="imgpath + 'store_icon.png?v=' + imgVersion" mode="aspectFit" > </image>
                <view class="txt">{{ objInfo.store.title }}</view>
            </view>
            <view class="order_state" v-if="stateTxt(objInfo) != '拼团中'">{{ stateTxt(objInfo) }}</view>
            <view class="order_djs" v-else>
                <view class="txt">仅剩：</view> 
                <view class="djs">
                    <view class="hh tbox">{{ djsObj.hh || '00' }}</view>
                    <text>:</text>
                    <view class="mm tbox">{{ djsObj.mm || '00' }}</view>
                    <text>:</text>
                    <view class="ss tbox">{{ djsObj.ss || '00' }}</view>
                </view>
            </view>
        </view>
        <view class="order-content">
            <view class="prosbox">
                <block v-if="objInfo.product.length == 1 || ['0','1','11'].includes(objInfo.orderstate)">
                    <view class="pros_detail flexb" v-for="(item,ind) in objInfo.product" :key="ind">
                        <image class="pro-img loadingImg" :src="item.litpic || defaultPro" mode="aspectFill"  @error="item.litpic = defaultPro "></image>
                        <view class="pro-info ">
                            <view class="pro_detail flexb">
                                <view class="flex_l">
                                    <view class="pro-tit">{{ item.title }}</view>
                                    <block v-if="objInfo.pinid!=0 && objInfo.pinstate==0 && objInfo.huodongarr && objInfo.huodongarr.chanume">
                                        <view class="pinListbox">
                                            <view class="plist">
                                                <view class="photo" v-for="(photo,ind) in objInfo.huodongarr.userarr" :key="'photo_' + ind"><image :src="photo || globalData.userError" @error="objInfo.huodongarr.userarr[ind] = globalData.userError"></image></view>
                                            </view>
                                            <view class="ptxt">差<text>{{ objInfo.huodongarr.chanume }}</text>人</view>
                                        </view>
                                    </block>
                                    <view class="pro-speci" v-else-if="item.specation">{{ specationText(item.specation) }}</view>
                                    <view class="pro-speci" v-else-if="objInfo.protype == 1 && objInfo.orderstate != 10&&objInfo.expireddate">有效期至：{{ objInfo.expireddate }}</view>
                                </view>
                                <view class="pro-price">
                                    <view class="price">{{globalData.appConfig && globalData.appConfig.currency && globalData.appConfig.currency.symbol || '￥'}}{{ item.price }}</view>
                                    <view class="num">x{{ item.count }}</view>
                                    <view v-if="objInfo.orderstate == '7'" class="tkcg">退款成功</view>
                                </view>
                            </view>
                            
                        </view>
                    </view>
                </block>
                <view class="proimgList flexb" v-else>
                    <image class="pro-img" v-for="(item,ind) in objInfo.product" :key="ind" :src="item.litpic || defaultPro" mode="aspectFill"  @error="item.litpic = defaultPro "></image>
                </view>
            </view>
            <view class="order-count flexb">
                <view class="flex_l">共<text class="txt">{{ objInfo.countall }}</text>件商品</view>
                <view class="flex_r flexb">
                    <text class="txt">{{objInfo.pinid != 0 ? '拼团价' : '实付'}}</text>
                    <view class="tprice">
                        <text class="symbol">{{globalData.appConfig && globalData.appConfig.currency && globalData.appConfig.currency.symbol || '￥'}}</text>
                        <text class="b">{{ objInfo.totalPayPrice.split('.')[0] }}</text>
                        <text class="smNumber" v-if=" objInfo.totalPayPrice.includes('.')">.{{  objInfo.totalPayPrice.split('.')[1] }}</text>
                    </view>
                </view>
            </view>
            <view class="btns_group flexb" >
                <block v-if="objInfo.orderstate == 0">
                    <view class="btn_cancel  btn" @click.stop="linkTo('cancel')">取消订单</view>
                    <view class="btn_cancel  btn" v-if="objInfo.huodongtype != 3 && objInfo.huodongtype != 4 && shopConfig && shopConfig.peerpayState == 1" @click.stop="linkTo('pay_other')">找人付</view>
                    <view class="btn_pay bgBtn  btn" @click.stop="linkTo('pay')">去付款</view>
                </block>
                <block v-else-if="objInfo.orderstate == 3">
                    <view class="btn_buy  btn" v-if="objInfo.common == '1'" @click.stop="linkTo('buy')">再次购买</view>
                    <view class="btn_common borderBtn btn" v-else @click.stop="linkTo('comment')">评价</view>
                </block>
                <view class="btn_tkStep" v-else-if="objInfo.orderstate == 4" @click.stop="linkTo('detail')">退款进度</view>
                <block v-else-if="objInfo.orderstate == 6 && objInfo.retState == 0 ">
                    <view class="btn_wuliu  btn" @click.stop="linkTo('wuliu')">查看物流</view>
                    <view class="btn_shou borderBtn btn" @click.stop="linkTo('receive')">确认收货</view>
                </block>
                <block v-else-if="objInfo.orderstate == 1">
                    <block v-if="objInfo.protype == 1 && objInfo.shopquan != 0">
                        <view class="btn_showID borderBtn btn" v-if="checkExpire(objInfo.expireddate || '')">查看券码</view>
                        <view class="btn_tuikuan  btn" v-else @click.stop="linkTo('refund')">申请退款</view>
                    </block>
                    <block v-if="objInfo.pinid!=0 && objInfo.pinstate==0 && checkExpire(objInfo.huodongarr.enddate,1)">
                        <button open-type="share" @click.stop="linkTo('share')" :data-orderInd="ind" style="margin-right: 0;" class="btn_invite bgBtn btn">邀请好友拼团</button>
                    </block>
                    <!-- <view class="btn_toDetail  btn" v-else >查看详情</view> -->
                </block>

                <block  v-else-if="objInfo.orderstate == 11 || (objInfo.orderstate == 6 && objInfo.reState == 1 && objInfo.protype  == 0 && objInfo.shopquan != 0)">
                    <view class="btn_toDetail  btn">查看详情</view>
                </block>
                
                
            </view>
        </view>
    </view>
</template>



<script>
    const app = getApp();
    export default {
        props:{
            objInfo:{
                type:Object,
                default:{
                    
                }
            },
            ind:{
                type:Number,
                default:0
            },
            shopConfig:{
                type:Object,
                default:{}
            }
        },
        data(){
            return {
                defaultPro:app.globalData.masterDomain + '/static/images/good_default.png',
                globalData:app.globalData,
                platForm:app.globalData.platForm,
                imgpath:app.globalData.imgPath + '/member/order/',
                masterDomain:app.globalData.masterDomain,
                imgVersion:app.globalData.imgVersion,
                djsObj:{
                    hh:'00',
                    mm:'00',
                    ss:'00'
                },
                interval:null
            }
        },
        computed:{
            stateTxt(){
                return function(order){
                    const that = this;
                    let txt = ''
                    if(!order) return '';

                    switch(order.orderstate){
                        case '0':
                            txt = '待付款'
                            break;
                        case '1':
                            txt = '待发货'
                            if(order.protype == 1){
                                if(order.shopquan != 0){
                                    let isExpired = that.checkExpire(order.expireddate || '')  
                                    txt = isExpired ?  '待使用' : '已过期'
                                }else{
                                    txt = '已使用'
                                }
                            }
                            if(order.pinid!=0 && order.pinstate==0){
                                txt = '拼团中';
                                if(!that.checkExpire(order.huodongarr.enddate,1)){
                                    txt = '拼团已失效';
                                }
							}
                            break;
                        case '3':
                            txt = order.common ? '交易完成' : '待评价'
                            break;
                        case '4':
                            txt = '退款中'
                            break;
                        case '6':
                            txt = order.retState == 1 ? '退款中' : '待收货'
                            break;
                        case '7':
                            txt = '交易关闭'
                            break;
                        case '10':
                            txt = '交易关闭'
                            break;
                        case '11':
                            txt = '待发货'
                            break;
                    }
                    return txt
                }
            },

            specationText(){
                return function(specation){
                    let speArr = specation.split(' ');
                    let speTxtArr = speArr.map(item => {
                        let pec = ''
                        let arr = item.split('：');
                        if(arr.length > 1){
                            pec = arr[1]
                        }
                        return pec;
                    })
                    return speTxtArr.join(';')
                }
            }
        },
        mounted(){
            this.djsText()
        },
        unmounted(){
            clearInterval(this.interval)
        },
        methods:{
            // 验证是否过期
            checkExpire(expireddate,type = 0){
                var expDateArr  = ''
                if(!type){

                    var Ret = new RegExp("\\.","g");//替换所有的点为-
                    // let expireddate = that.objInfo.expireddate || ''
                    expireddate = expireddate.replace(Ret,"-")
                    expDateArr = (new Date(expireddate)).getTime();
                }else{
                    expDateArr = expireddate * 1000
                }
                var nowDateArr = (new Date()).getTime();
                return expDateArr > nowDateArr
            },

            linkTo(type){
                const that = this;
                if(type == 'detail'){
                    // 订单详情
                    let url = that.globalData.appConfig.cfg_user_index + '/orderdetail-shop-' + that.objInfo.id;
                    app.linkTo(url,false,false)
                }else if(type == 'store'){
                    let url = that.objInfo.store.domain
                    if(app.globalData.platForm != 'web'){
                        url = '/pages/packages/shop/store-detail/store-detail?id=' + that.objInfo.store.id
                    }
                    app.linkTo(url,false,false)
                }else if(type == 'pay_other'){
                    // 订单详情
                    let url = that.globalData.appConfig.cfg_user_index + '/daipay.html?module=shop&ordernum=' + that.objInfo.ordernum;
                    app.linkTo(url,false,false)
                }else if(type == 'pay'){
                    // 支付订单
                    uni.$emit('payorder',{objInfo:this.objInfo,ind:this.ind})
                }else if(type == 'cancel'){
                    // 取消订单
                    uni.$emit('cancelorder',{objInfo:this.objInfo,ind:this.ind})
                }else if(type == 'buy'){
                    // 再次购买
                    that.rebuy()
                }else if(type == 'comment'){
                    // 评价
                    let url = that.globalData.appConfig.cfg_user_index + '/write-comment-shop-' + that.objInfo.id;
                    app.linkTo(url,false,false)
                }else if(type == 'refund'){
                    // 退款
                    let url = that.globalData.appConfig.cfg_user_index + '/orderdetail-shop-' + that.objInfo.id;
                    app.linkTo(url,false,false)
                }else if(type == 'receive'){
                    // 确认收货
                    uni.$emit('receive',{objInfo:this.objInfo,ind:this.ind})
                }else if(type == 'wuliu'){
                    let url = `${app.globalData.appConfig.cfg_user_index}/logistics.html?oid=${that.objInfo.id}`;
                    app.linkTo(url,false,false)
                }else if(type == 'share'){
                    if(app.globalData.platForm == 'web'){
                        uni.$emit('share',{objInfo:this.objInfo,ind:this.ind})
                    }
                }
            },
            djsText(){
                const that = this
                if(that.interval){
                    clearInterval(that.interval); //清除定时器
                }
                if(that.objInfo.orderstate == '1' && that.objInfo.pinid!=0 &&that.objInfo.pinstate==0){
                    let enddate = that.objInfo.huodongarr.enddate; 
                    let now = parseInt(new Date().getTime() / 1000)
                    if(enddate <= now){
                        clearInterval(that.interval)
                        return false;
                    }
                    
                    that.interval = setInterval(() => {
                        let nowdate = parseInt(new Date().getTime() / 1000)
                        let off = enddate - nowdate;
                        if( off < 0) {
                            clearInterval(that.interval);
                            return false
                        }
                        let hh = parseInt(off / 60 / 60);
                            hh = hh > 9 ? hh : ('0' + hh)
                        let mm = parseInt(off / 60 % 60)
                            mm = mm > 9 ? mm : ('0' + mm)
                        let ss = parseInt(off % 60)
                            ss = ss > 9 ? ss : ('0' + ss)
                        that.djsObj  = {
                            hh:hh,
                            mm:mm,
                            ss:ss
                        }

                    },1000)
                }
            },

            async rebuy(){
                const that = this;
                let cartList = uni.getStorageSync('shopCartList');
                if(cartList && typeof(cartList) == 'string'){
                    cartList = JSON.parse(cartList)
                }else{
                    let url = 'service=shop&action=getCartList'
                    var urlData = app.encodeUrl(url);
                    let result = await that.$ajax.post({
                        url: 'include/ajax.php?' , //请求地址
                        data:urlData,
                    });
                    let data = result.data;
                    if(data.state == 100){
                        cartList = data.info;
                    }
                }
                cartList = Array.isArray(cartList) ? cartList : [];
                let cartobj = {};
                // 循环购物车
                for(let i = 0; i < cartList.length; i++){
                    let pro = cartList[i]
                    cartobj[pro.id] = [{
                        id:pro.id,
                        specation:pro.specation || '',
                        count:pro.count * 1
                    }]
                }

                // 循环加购的商品
                let product = that.objInfo.product;
                for(let i = 0; i < product.length; i++){
                    let pro = product[i];
                    // 表示已存在
                    if(cartobj[pro.proid]){
                        if(pro.speid){
                            let list = cartobj[pro.proid];
                            let speInd = list.findIndex(item => {
                                return item['specation'] == pro.speid
                            })
                            if(speInd <= -1){
                                list.push({
                                    id:pro.proid,
                                    specation:pro.speid || '',
                                    count:pro.count * 1
                                })
                            }else{
                                cartobj[pro.proid][speInd].count = cartobj[pro.proid][speInd].count + pro.count
                            }
                        }else{
                            cartobj[pro.proid][0].count = cartobj[pro.proid][0].count + pro.count
                        }
                    }else{
                        cartobj[pro.proid] = [{
                            id:pro.proid,
                            specation:pro.speid || '',
                            count:pro.count * 1
                        }]
                    }
                }

                let proArr = [];
                for(let item in cartobj){
                    for(let i = 0; i < cartobj[item].length; i++){
                        proArr.push(`${cartobj[item][i].id},${cartobj[item][i].specation},${cartobj[item][i].count}`)
                    }
                }
                that.addCart(proArr.join('|'))
            },
            async addCart(cartStr){
                const that = this;
                let url = `service=member&action=operateCart&module=shop&type=update&content=${cartStr}`
                var urlData = app.encodeUrl(url);
                    let result = await that.$ajax.post({
                        url: 'include/ajax.php?' , //请求地址
                        data:urlData,
                    });
                    let data = result.data;
                    if(data.state == 100){
                        uni.showToast({
                            title: '成功加入购物车',
                            duration: 2000,
                            icon:'none',
                            success: function() {
                                if(app.platForm == 'web'){
                                    let url = `${masterDomain}/shop/cart`;
                                    app.linkTo(url,false,false)
                                }else{
                                    let url = '/pages/packages/shop/cart/cart';
                                    uni.navigateTo({
                                        url: url
                                    });
                                }
                            }
                        });
                    }
            },
        }
    }
</script>

<style scoped>
    @import './orderlist_shop.css'
</style>